<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>SpirngBoot WebSocket</title>
</head>
<body>
<noscript><h2 style="color: #ff0000">貌似你的浏览器不支持websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv">
        <label>输入你的名字</label><input type="text" id="name"/>
        <button id="sendName" onclick="sendName();">发送</button>
    </div>
    <div>
        <h3 id="response"></h3>
    </div>
</div>

<script th:src="@{/js/sockjs.min.js}"></script>
<script th:src="@{/js/stomp.min.js}"></script>
<script th:src="@{/js/jquery-1.9.1.js}"></script>

<script type="text/javascript">

    let stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $('#response').html();
    }

    function connect() {
        let socket = new SockJS('http://127.0.0.1:8082/socket'); //1
        stompClient = Stomp.over(socket);//2
        stompClient.connect({}, function (frame) {//3
            setConnected(true);
            console.log('开始进行连接Connected: ' + frame);
            stompClient.subscribe('/topic/notice', function (response) { //4 接收信息
                showResponse(JSON.parse(response.body).name);
            });
        });
    }

    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        let name = $('#name').val();
        stompClient.send("/app/change-notice", {}, JSON.stringify({'name': name}));//5 发送信息
    }

    function showResponse(message) {
        let response = $("#response");
        response.html(message);
    }
</script>
</body>
</html>
